package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.annotation.AdminLog;
import com.zt.common.Result;
import com.zt.dto.SubjectQueryRequest;
import com.zt.entity.Subjects;
import com.zt.service.SubjectsService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 科目管理控制器
 * @author 周明震
 * @date 2025/7/21
 */
@RestController
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectsService subjectsService;

    /**
     * 分页查询科目列表
     */
    @PostMapping("/list")
    public Result<IPage<Subjects>> list(@RequestBody SubjectQueryRequest request) {
        try {
            Page<Subjects> pageParam = new Page<>(request.getPage(), request.getSize());
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();

            // 按名称模糊查询
            if (request.getName() != null && !request.getName().trim().isEmpty()) {
                queryWrapper.like("name", request.getName().trim());
            }

            // 按年级层次查询
            if (request.getGradeLevel() != null) {
                queryWrapper.eq("grade_level", request.getGradeLevel());
            }

            // 按状态查询
            if (request.getStatus() != null) {
                queryWrapper.eq("status", request.getStatus());
            }

            // 按排序号升序排列
            queryWrapper.orderByAsc("sort_order", "id");

            IPage<Subjects> result = subjectsService.page(pageParam, queryWrapper);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有科目列表（不分页）
     */
    @GetMapping("/all")
    public Result<List<Subjects>> getAllSubjects() {
        try {
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1); // 只查询启用的科目
            queryWrapper.orderByAsc("sort_order", "id");

            List<Subjects> list = subjectsService.list(queryWrapper);
            return Result.success("查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询科目详情
     */
    @GetMapping("/{id}")
    public Result<Subjects> getById(@PathVariable Integer id) {
        try {
            Subjects subject = subjectsService.getById(id);
            if (subject == null) {
                return Result.error("科目不存在");
            }
            return Result.success("查询成功", subject);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增科目
     */
    @PostMapping("/add")
    @AdminLog(module = "科目管理", operation = "新增", description = "新增科目", type = AdminLog.OperationType.CREATE)
    public Result<String> add(@RequestBody Subjects subject) {
        try {
            // 验证必填字段
            if (subject.getName() == null || subject.getName().trim().isEmpty()) {
                return Result.error("科目名称不能为空");
            }

            // 检查科目名称是否已存在
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", subject.getName().trim());
            if (subjectsService.count(queryWrapper) > 0) {
                return Result.error("科目名称已存在");
            }

            // 设置默认值
            if (subject.getStatus() == null) {
                subject.setStatus(1);
            }
            if (subject.getSortOrder() == null) {
                subject.setSortOrder(0);
            }

            boolean success = subjectsService.save(subject);
            if (success) {
                return Result.success("新增成功");
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 更新科目
     */
    @PostMapping("/update")
    @AdminLog(module = "科目管理", operation = "修改", description = "修改科目信息", type = AdminLog.OperationType.UPDATE)
    public Result<String> update(@RequestBody Subjects subject) {
        try {
            if (subject.getId() == null) {
                return Result.error("科目ID不能为空");
            }

            // 验证科目是否存在
            Subjects existingSubject = subjectsService.getById(subject.getId());
            if (existingSubject == null) {
                return Result.error("科目不存在");
            }

            // 验证必填字段
            if (subject.getName() == null || subject.getName().trim().isEmpty()) {
                return Result.error("科目名称不能为空");
            }

            // 检查科目名称是否已被其他科目使用
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", subject.getName().trim());
            queryWrapper.ne("id", subject.getId());
            if (subjectsService.count(queryWrapper) > 0) {
                return Result.error("科目名称已存在");
            }

            boolean success = subjectsService.updateById(subject);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除科目
     */
    @PostMapping("/delete/{id}")
    @AdminLog(module = "科目管理", operation = "删除", description = "删除科目", type = AdminLog.OperationType.DELETE)
    public Result<String> delete(@PathVariable Integer id) {
        try {
            if (id == null) {
                return Result.error("科目ID不能为空");
            }

            // 验证科目是否存在
            Subjects subject = subjectsService.getById(id);
            if (subject == null) {
                return Result.error("科目不存在");
            }

            // TODO: 检查是否有教师关联此科目，如果有则不能删除
            // 这里可以添加业务逻辑检查

            boolean success = subjectsService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除科目
     */
    @PostMapping("/batchDelete")
    @AdminLog(module = "科目管理", operation = "批量删除", description = "批量删除科目", type = AdminLog.OperationType.DELETE)
    public Result<String> batchDelete(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的科目");
            }

            // TODO: 检查是否有教师关联这些科目，如果有则不能删除

            boolean success = subjectsService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 更新科目状态
     */
    @PostMapping("/updateStatus")
    @AdminLog(module = "科目管理", operation = "状态变更", description = "更新科目状态", type = AdminLog.OperationType.UPDATE)
    public Result<String> updateStatus(@RequestParam Integer id, @RequestParam Integer status) {
        try {
            if (id == null) {
                return Result.error("科目ID不能为空");
            }

            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }

            Subjects subject = subjectsService.getById(id);
            if (subject == null) {
                return Result.error("科目不存在");
            }

            subject.setStatus(status);
            boolean success = subjectsService.updateById(subject);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("状态更新失败：" + e.getMessage());
        }
    }

    /**
     * 根据年级层次查询科目
     */
    @GetMapping("/byGrade/{gradeLevel}")
    public Result<List<Subjects>> getByGradeLevel(@PathVariable Integer gradeLevel) {
        try {
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("grade_level", gradeLevel);
            queryWrapper.eq("status", 1); // 只查询启用的科目
            queryWrapper.orderByAsc("sort_order", "id");

            List<Subjects> list = subjectsService.list(queryWrapper);
            return Result.success("查询成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 导出科目数据为Excel
     */
    @GetMapping("/export")
    public void exportSubjectData(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "gradeLevel", required = false) Integer gradeLevel,
            @RequestParam(value = "status", required = false) Integer status,
            HttpServletResponse response) {
        try {
            // 构建查询条件
            QueryWrapper<Subjects> queryWrapper = new QueryWrapper<>();

            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name.trim());
            }

            if (gradeLevel != null) {
                queryWrapper.eq("grade_level", gradeLevel);
            }

            if (status != null) {
                queryWrapper.eq("status", status);
            }

            // 按排序号升序排列
            queryWrapper.orderByAsc("sort_order", "id");

            // 查询科目数据
            List<Subjects> subjects = subjectsService.list(queryWrapper);

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("科目数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {
                "科目ID", "科目名称", "年级层次", "排序号", "状态"
            };

            // 创建标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);

            // 设置标题
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 4000); // 设置列宽
            }

            // 创建数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);

            // 填充数据
            int rowNum = 1;
            for (Subjects subject : subjects) {
                Row row = sheet.createRow(rowNum++);

                // 科目ID
                Cell cell0 = row.createCell(0);
                cell0.setCellValue(subject.getId() != null ? subject.getId() : 0);
                cell0.setCellStyle(dataStyle);

                // 科目名称
                Cell cell1 = row.createCell(1);
                cell1.setCellValue(subject.getName() != null ? subject.getName() : "");
                cell1.setCellStyle(dataStyle);

                // 年级层次
                Cell cell2 = row.createCell(2);
                String gradeName = getGradeLevelName(subject.getGradeLevel());
                cell2.setCellValue(gradeName);
                cell2.setCellStyle(dataStyle);

                // 排序号
                Cell cell3 = row.createCell(3);
                cell3.setCellValue(subject.getSortOrder() != null ? subject.getSortOrder() : 0);
                cell3.setCellStyle(dataStyle);

                // 状态
                Cell cell4 = row.createCell(4);
                String statusText = subject.getStatus() != null && subject.getStatus() == 1 ? "启用" : "禁用";
                cell4.setCellValue(statusText);
                cell4.setCellStyle(dataStyle);
            }

            // 设置响应头
            String fileName = "科目数据_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 写入响应
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取年级层次名称
     */
    private String getGradeLevelName(Integer gradeLevel) {
        if (gradeLevel == null) {
            return "未知";
        }
        switch (gradeLevel) {
            case 1: return "小学";
            case 2: return "初中";
            case 3: return "高中";
            default: return "未知";
        }
    }
}
